<?php

namespace app\controller\workorder;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

/**
 * 工单分配历史管理
 */
class AssignmentHistory extends BaseController
{
    /**
     * 获取分配历史列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $workOrderNo = $params['work_order_no'] ?? '';
        $assignmentType = $params['assignment_type'] ?? '';
        $operatorId = $params['operator_id'] ?? '';

        $query = Db::name('work_order_assignment_history')
            ->alias('wah')
            ->field('wah.*, wo.work_order_no, wo.title as work_order_title, a1.name as from_assignee_name, a2.name as to_assignee_name, a3.name as operator_name')
            ->leftJoin('work_order wo', 'wah.work_order_id = wo.id')
            ->leftJoin('admin a1', 'wah.from_assignee_id = a1.id')
            ->leftJoin('admin a2', 'wah.to_assignee_id = a2.id')
            ->leftJoin('admin a3', 'wah.operator_id = a3.id');

        if ($workOrderNo) {
            $query->where('wo.work_order_no', 'like', '%' . $workOrderNo . '%');
        }

        if ($assignmentType) {
            $query->where('wah.assignment_type', $assignmentType);
        }

        if ($operatorId) {
            $query->where('wah.operator_id', $operatorId);
        }

        $total = $query->count();
        $list = $query->order('wah.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }

    /**
     * 获取工单概览统计数据
     */
    public function stats()
    {
        // 总工单数
        $total = Db::name('work_order')->count();

        // 进行中工单数
        $inProgress = Db::name('work_order')
            ->where('status', 2)
            ->count();

        // 已完成工单数
        $completed = Db::name('work_order')
            ->where('status', 3)
            ->count();

        // 待分配工单数
        $pending = Db::name('work_order')
            ->where('status', 1)
            ->count();

        return $this->success([
            'total' => $total,
            'in_progress' => $inProgress,
            'completed' => $completed,
            'pending' => $pending
        ]);
    }

    /**
     * 获取工单的分配历史
     */
    public function getWorkOrderHistory()
    {
        $workOrderId = Request::param('work_order_id');
        if (!$workOrderId) {
            return $this->error('参数错误');
        }

        $history = Db::name('work_order_assignment_history')
            ->alias('wah')
            ->field('wah.*, a1.name as from_assignee_name, a2.name as to_assignee_name, a3.name as operator_name')
            ->leftJoin('admin a1', 'wah.from_assignee_id = a1.id')
            ->leftJoin('admin a2', 'wah.to_assignee_id = a2.id')
            ->leftJoin('admin a3', 'wah.operator_id = a3.id')
            ->where('wah.work_order_id', $workOrderId)
            ->order('wah.create_time', 'desc')
            ->select();

        return $this->success($history ? $history->toArray() : []);
    }

    /**
     * 获取所有部门工单分配统计
     */
    public function departmentStats()
    {
        // 获取所有部门
        $departments = Db::name('department')
            ->field('id, name')
            ->select()
            ->toArray();

        $departmentStats = [];

        foreach ($departments as $dept) {
            // 获取部门下的工单
            $workOrders = Db::name('work_order')
                ->field('id, work_order_no, status')
                ->where('department_manager_id', 'in', function($query) use ($dept) {
                    $query->name('admin')
                        ->where('did', $dept['id'])
                        ->field('id');
                })
                ->select()
                ->toArray();

            $workOrderIds = array_column($workOrders, 'id');

            if (empty($workOrderIds)) {
                $departmentStats[] = [
                    'department_name' => $dept['name'],
                    'total_orders' => 0,
                    'completed_orders' => 0,
                    'completion_rate' => 0,
                    'avg_hours' => 0
                ];
                continue;
            }

            // 总工单数
            $totalOrders = count($workOrderIds);

            // 已完成数
            $completedOrders = Db::name('work_order')
                ->where('id', 'in', $workOrderIds)
                ->where('status', 3)
                ->count();

            // 计算完成率
            $completionRate = $totalOrders > 0 ? round(($completedOrders / $totalOrders) * 100, 2) : 0;

            // 获取已完成工单的平均处理时间
            $completedWorkOrders = Db::name('work_order')
                ->where('id', 'in', $workOrderIds)
                ->where('status', 3)
                ->where('actual_end_time', '>', 0)
                ->field('create_time, actual_end_time')
                ->select()
                ->toArray();

            $avgHours = 0;
            if (!empty($completedWorkOrders)) {
                $totalHours = 0;
                foreach ($completedWorkOrders as $wo) {
                    $totalHours += ($wo['actual_end_time'] - $wo['create_time']) / 3600;
                }
                $avgHours = round($totalHours / count($completedWorkOrders), 1);
            }

            $departmentStats[] = [
                'department_name' => $dept['name'],
                'total_orders' => $totalOrders,
                'completed_orders' => $completedOrders,
                'completion_rate' => $completionRate,
                'avg_hours' => $avgHours
            ];
        }

        return $this->success($departmentStats);
    }

    /**
     * 获取员工工单分配统计（Top 10）
     */
    public function employeeStats()
    {
        // 获取所有有工单的员工
        $employees = Db::name('work_order')
            ->alias('wo')
            ->field('wo.assignee_id, a.name')
            ->leftJoin('admin a', 'wo.assignee_id = a.id')
            ->where('wo.assignee_id', '>', 0)
            ->group('wo.assignee_id')
            ->select()
            ->toArray();

        $employeeStats = [];

        foreach ($employees as $emp) {
            $employeeId = $emp['assignee_id'];

            // 分配给该员工的工单总数
            $totalAssigned = Db::name('work_order')
                ->where('assignee_id', $employeeId)
                ->count();

            // 已完成的工单数
            $completed = Db::name('work_order')
                ->where('assignee_id', $employeeId)
                ->where('status', 3)
                ->count();

            // 计算完成率
            $completionRate = $totalAssigned > 0 ? round(($completed / $totalAssigned) * 100, 2) : 0;

            // 获取已完成工单的平均处理时间
            $completedWorkOrders = Db::name('work_order')
                ->where('assignee_id', $employeeId)
                ->where('status', 3)
                ->where('actual_end_time', '>', 0)
                ->field('create_time, actual_end_time')
                ->select()
                ->toArray();

            $avgHours = 0;
            if (!empty($completedWorkOrders)) {
                $totalHours = 0;
                foreach ($completedWorkOrders as $wo) {
                    $totalHours += ($wo['actual_end_time'] - $wo['create_time']) / 3600;
                }
                $avgHours = round($totalHours / count($completedWorkOrders), 1);
            }

            $employeeStats[] = [
                'id' => $employeeId,
                'name' => $emp['name'] ?? '未知',
                'total_assigned' => $totalAssigned,
                'completed' => $completed,
                'completion_rate' => $completionRate,
                'avg_hours' => $avgHours
            ];
        }

        // 按完成数降序排序，取前10名
        usort($employeeStats, function($a, $b) {
            return $b['completed'] - $a['completed'];
        });

        $topEmployees = array_slice($employeeStats, 0, 10);

        return $this->success([
            'top_employees' => $topEmployees
        ]);
    }

    /**
     * 获取工单效率分析
     */
    public function efficiencyAnalysis()
    {
        // 按部门统计
        $departmentStats = Db::query('
            SELECT d.title as department_name,
                   COUNT(wo.id) as total_orders,
                   SUM(CASE WHEN wo.status = 3 THEN 1 ELSE 0 END) as completed_orders,
                   AVG(CASE WHEN wo.start_time > 0 AND wo.actual_end_time > 0
                       THEN (wo.actual_end_time - wo.start_time) / 3600
                       ELSE NULL END) as avg_hours
            FROM oa_department d
            LEFT JOIN oa_admin a ON d.id = a.did
            LEFT JOIN oa_work_order wo ON a.id = wo.department_manager_id
            WHERE d.id IN (3, 4)
            GROUP BY d.id, d.title
        ');

        // 按员工统计（前10名）
        $employeeStats = Db::query('
            SELECT a.name,
                   COUNT(wo.id) as total_assigned,
                   SUM(CASE WHEN wo.status = 3 THEN 1 ELSE 0 END) as completed,
                   AVG(CASE WHEN wo.start_time > 0 AND wo.actual_end_time > 0
                       THEN (wo.actual_end_time - wo.start_time) / 3600
                       ELSE NULL END) as avg_hours
            FROM oa_admin a
            LEFT JOIN oa_work_order wo ON a.id = wo.assignee_id
            WHERE wo.id IS NOT NULL
            GROUP BY a.id, a.name
            ORDER BY completed DESC
            LIMIT 10
        ');

        return $this->success([
            'department_stats' => $departmentStats,
            'employee_stats' => $employeeStats
        ]);
    }
}
